import dayjs from 'dayjs'

const myUtil = {
  /**
   * @param [Int, String] d 时间
   * @description 将时间戳或时间字符串转换为dayjs对象
   * @return {dayjs}
   */
  $dayjs(d) {
    if (!d) {
      return dayjs()
    }
    if (parseInt(d) == d && (d + '').length == 10) {
      return dayjs(d * 1000)
    }
    if (d && (d + '').indexOf('T') > -1) {
      let str = (d + '').replace(/T/g, ' ')
      let d1 = str.split('.')[0]
      return dayjs(d1)
    }
    return dayjs(d)
  },
  /**
   * @desc 函数防抖
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param immediate true 表立即执行，false 表非立即执行
   */
  debounce(func, wait = 300, immediate) {
    let timeout

    return function () {
      let context = this
      let args = arguments

      if (timeout) clearTimeout(timeout)
      if (immediate) {
        var callNow = !timeout
        timeout = setTimeout(() => {
          timeout = null
        }, wait)
        if (callNow) func.apply(context, args)
      } else {
        timeout = setTimeout(function () {
          func.apply(context, args)
        }, wait)
      }
    }
  },
  /**
   * @desc 函数节流
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param type 1 表时间戳版，2 表定时器版
   */
  throttle(func, wait = 300, type) {
    if (type === 1) {
      let previous = 0
    } else if (type === 2) {
      let timeout
    }
    return function () {
      let context = this
      let args = arguments
      if (type === 1) {
        let now = Date.now()

        if (now - previous > wait) {
          func.apply(context, args)
          previous = now
        }
      } else if (type === 2) {
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null
            func.apply(context, args)
          }, wait)
        }
      }
    }
  },
  // 下载文件
  downloadFile(url, download = '') {
    var x = new XMLHttpRequest()
    x.open('GET', url, true)
    x.responseType = 'blob'
    x.onload = function (e) {
      //会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
      var url = window.URL.createObjectURL(x.response)
      var a = document.createElement('a')
      a.href = url
      a.download = download
      a.click()
    }
    x.send()
  },
  downloadImage(url) {
    console.log('on downloadHandler')
    uni.getSetting({
      success: settings => {
        if (!settings.authSetting['scope.writePhotosAlbum']) {
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success: authRes => {
              this.wxDownload(url)
            }
          })
        } else {
          this.wxDownload(url)
        }
      }
    })
  },
  wxDownload(url) {
    uni.downloadFile({
      url,
      success: (res) => {
        if (res.statusCode == 200) {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: (saveRes) => {
              console.log('saveRes:', saveRes)
              uni.$u.toast('保存成功')
            }
          })
        }
      }
    })
  },
}

export default myUtil
